package com.nali.dal.mongo.explain.operate;

import java.util.Collections;
import java.util.List;

import org.apache.log4j.Logger;

import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;
import com.nali.dal.mongo.explain.query.Condition;

public class PreparedUpdate {
	private static Logger logger = Logger.getLogger(PreparedUpdate.class);
	private Condition condition;
	private Operate operate;
	
	public PreparedUpdate(Condition condition, Operate operate) {
		super();
		this.condition = condition;
		this.operate = operate;
	}
	
	/**
	 * @param params 先应用查询参数再应用更新参数
	 */
	public int update(List<Object> params, DBCollection collection, boolean upsert, WriteConcern concern) throws MongoException {
		DBObject query = condition.getQueryDBObject(params);
		DBObject modifiers = operate.getOperateDBObject(params, condition.getParamsLength());
		if(logger.isDebugEnabled()) {
			logger.debug("collection:" + collection.getName());
			logger.debug("query:" + query);
			logger.debug("modifiers:" + modifiers);
		}
		WriteResult result = collection.update(query, modifiers, upsert, true, concern);
		return result.getN();
	}
	
	public int update(DBCollection collection, boolean upsert, WriteConcern concern) throws MongoException {
		return update(Collections.emptyList(), collection, upsert, concern);
	}

	public int getConditionParamSize() {
		return condition.getParamsLength();
	}
}
